package model.inventory;

import java.util.LinkedList;
import java.util.List;

import model.inventory.item.Item;

public class Inventory {
	private List<Item> items;
	private Item selectedItem;
	
	public Inventory(){
		items = new LinkedList<Item>();
	}

	public void add(Item item) {
		if(item == null)
			return;
		Item exists = findItem(item.getID());
		if(exists != null)
			exists.add(item.getQuantity());
		else
			items.add(item);
	}

	public Item remove(Item item){
		Item exists = findItem(item.getID());
		if(exists != null){
			if(exists.getQuantity() > item.getQuantity() || exists.getQuantity() == -1){
				exists.remove(item.getQuantity());
				return item;
			}else if(exists.getQuantity() == item.getQuantity()){
				if(exists == selectedItem)
					selectedItem = null;
				items.remove(exists);
				return item;
			}else{
				if(exists == selectedItem)
					selectedItem = null;
				items.remove(exists);
				return exists;
			}
		}
		return null;
	}
	
	public Item getSelectedItem(){
		return selectedItem;
	}
	
	public Item getItem(int i){
		return items.get(i);
	}

	public Item findItem(int itemID){
		for(Item i : items){
			if(i.getID() == itemID){
				return i;
			}
		}
		return null;
	}

	public Inventory subInventory(int quantity) {
		Inventory sub = new Inventory();
		for(int i = 0; i < items.size(); ){
			Item item = items.get(i);
			if(item.getQuantity() > quantity || item.getQuantity() == -1)
				i++;
			sub.add(this.remove(new Item(item.getID(), quantity)));
		}
		return sub;
	}

	public void add(Inventory transaction) {
		for(int i = 0; i < transaction.items.size();){
			Item item = transaction.items.get(i);
			this.add(transaction.remove(item));
		}
	}

	public boolean isEmpty() {
		return items.isEmpty();
	}

	public int size() {
		return items.size();
	}

	public boolean contains(Item item){
		if(this.findItem(item.getID()) == null){
			if(item.getQuantity() == 0)
				return true;
			return false;
		}
		if(item.getQuantity() != this.findItem(item.getID()).getQuantity())
			return false;
		return true;
	}
	
	public void setSelected(int itemID){
		selectedItem = this.findItem(itemID);
	}
}
